package com.caration.shell.settings;

import android.provider.Settings;

import com.caration.shell.ShellHandler;
import com.caration.shell.cr3d.RenderRunnable;
import com.caration.shell.cr3d.SharedData;

public final class AirplaneModeManager {
	private static final String SYNC = "sync";
	private static AirplaneModeManager sInstance;
	private int mState;
	private IconTexture mIconTexture;
	private RenderRunnable mRenderRun;

	public static AirplaneModeManager getInstance() {
		synchronized (SYNC) {
			if (sInstance == null)
				sInstance = new AirplaneModeManager();
		}
		return sInstance;
	}

	public final void init(IconTexture iconTexture) {
		mIconTexture = iconTexture;
		try {
			mState = Settings.System.getInt(SharedData.getContext()
					.getContentResolver(), Settings.System.AIRPLANE_MODE_ON);
		} catch (Exception e) {
			e.printStackTrace();
			return;
		}

		updateIcon();
	}

	public final void updateIcon() {
		if (mIconTexture != null)
			switch (mState) {
			default:
				mIconTexture.setupTexture(2);
				break;

			case 0: // '\0'
				mIconTexture.setupTexture(0);
				break;

			case 1: // '\001'
				mIconTexture.setupTexture(1);
				break;
			}
	}

	/**
	 * 更新状态 刷新图标
	 */
	public final void update() {
		if (SharedData.getContext() != null
				&& SharedData.getGLHandler() != null) {
			if (!android.provider.Settings.System.getString(
					SharedData.getContext().getContentResolver(),
					"airplane_mode_on").equals("0"))
				mState = 1;
			else
				mState = 0;
			if (mRenderRun != null) {
				SharedData.getGLHandler().queueEvent(mRenderRun);
				mRenderRun = null;
			}
			mRenderRun = new RenderRunnable(2, RenderRunnable.TYPE_GL_THREAD) {
				public void run() {
					updateIcon();
					mRenderRun = null;
				};
			};
			if (ShellHandler.getInstance().b())
				mRenderRun.mAutoInvalidate = true;
			SharedData.getGLHandler().post(mRenderRun);
			if (mIconTexture != null) {
				// mIconTexture.q();
			}
		}
	}

}
